/***************************************************************************
 *            ddns.c
 *
 *  Mon May 22 12:14:44 2007
 *  Copyright  2007  kf701
 *  Email kf_701@21cn.com
 ****************************************************************************/

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <glib.h>

#include "kf701.h"

GHashTable * table;

/* data protocol: userid=xxx\r\n */
void run(struct sockaddr *addr, uint8_t *data, uint32_t size)
{
	gchar *userid = g_malloc0( 32 );
	if ( 1 != sscanf( (const char*)data, "userid=%s", userid ) )
	{
		sys_warn("bad user data\n");
		g_free( userid );
		return;
	}
	gpointer value = g_malloc0( sizeof(struct sockaddr) );
	memcpy( value, addr, sizeof(struct sockaddr) );
	g_hash_table_insert( table, userid, value );
}

int main(int argc, char **argv)
{
	bool background = false;
	uint16_t port = 8080;
	debug_verbose = 4;

	void usage()
	{
		printf("Usage: ddns.out -p port -d debug_level -b\n");
		exit( 0 );
	}

	int opt;
	opterr = 0;
	while ((opt = getopt (argc, argv, "d:p:b")) != -1)
	{
		switch (opt)
		{
			case 'b':
				background = true;
				break;
			case 'd':
				debug_verbose = atoi( optarg );
				break;
			case 'p':
				port = (uint16_t)atoi( optarg );
				break;
			case 'h':
				usage();
				break;
			default:
				;
		}
	}

	if( background )
		daemon( 0, 0 );

	table = g_hash_table_new_full(g_str_hash,g_str_equal,g_free,g_free);

	sys_log("start,listen port %d ...\n",port);
	udp_server( port, 1024, run );

	return 0;
}
